<template>
  <lam-dialog :visible.sync="visible" title="修改密码" :close-on-click-modal="false" width="400px" append-to-body @close="close">
    <el-form ref="form" :model="user" :rules="rules" label-width="80px" @keyup.enter.native="submit">
      <el-form-item label="旧密码" prop="oldLoginPwd">
        <el-input v-model="user.oldLoginPwd" placeholder="请输入旧密码" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newLoginPwd">
        <el-input v-model="user.newLoginPwd" placeholder="请输入新密码" type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmLoginPwd">
        <el-input v-model="user.confirmLoginPwd" placeholder="请确认密码" type="password" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary"  @click="submit" :loading="loading">确 定</el-button>
      <el-button type="danger"  @click="close" :loading="loading">取 消</el-button>
    </div>
  </lam-dialog>
</template>

<script>
import { updateUserPwd } from "@/api/system/user";

export default {
  data() {
    return {
      name: "updatePwd",
      visible: false,
      loading: false,
      user: {
        oldLoginPwd: undefined,
        newLoginPwd: undefined,
        confirmLoginPwd: undefined
      },
      // 表单校验
      rules: {
        oldLoginPwd: [
          { required: true, message: "旧密码不能为空", trigger: "blur" }
        ],
        newLoginPwd: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        confirmLoginPwd: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: this.comparePwd, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          updateUserPwd(this.md5(this.user.oldLoginPwd), this.md5(this.user.newLoginPwd)).then(response => {
            this.msgSuccess("修改成功");
            this.close()
          }).finally(res=>{
            this.loading = false;
          });
        }
      });
    },
    comparePwd(rule, value, callback) {
      if (this.user.newLoginPwd !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    open(){
      this.user = {}
      this.visible = true;
    },
    close() {
      this.user = {}
      this.visible = false;
      this.$refs["form"].clearValidate()
    }
  }
};
</script>
